package com.source.labelAndBarcode.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.source.baseData.entity.BarcodeMachine;
import com.source.baseData.entity.PoultryCategoryParent;
import com.source.baseData.entity.SlaughterHouse;
import com.source.baseData.entity.Stalls;
import com.source.baseData.service.BarcodeMachineService;
import com.source.baseData.service.PoultryCategoryParentService;
import com.source.baseData.service.SlaughterHouseService;
import com.source.baseData.service.StallsService;
import com.source.baseData.vo.PoultryParentVo;
import com.source.labelAndBarcode.entity.BarcodeRevoke;
import com.source.labelAndBarcode.entity.LabelingRecord;
import com.source.labelAndBarcode.service.LabelingRecordService;
import com.source.labelAndBarcode.vo.*;
import com.source.utils.CommonResult;
import com.source.utils.ResultEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Joey
 * @since 2021-02-23
 */
@Api(tags = "贴标信息管理")
@CrossOrigin
@RestController
@RequestMapping("/labelAndBarcode/labeling-record")
public class LabelingRecordController {

    @Autowired
    LabelingRecordService recordService;

    @Autowired
    PoultryCategoryParentService parentService;


    @ApiOperation(value = "根据一系列关键词，以日期分组查询某个时间段贴标的数量", notes = "第二版本")
    @GetMapping("/findCountsGroupByDay")
    public CommonResult<Object> findCountsGroupByDay(@RequestParam(value = "stallsName", required = false) String stallsName,
                                                     @RequestParam(value = "contacts", required = false) String contacts,
                                                     @RequestParam(value = "startDate", required = false) Date startDate,
                                                     @RequestParam(value = "endDate", required = false) Date endDate,
                                                     @RequestParam(value = "current", defaultValue = "1") Integer current,
                                                     @RequestParam(value = "size", defaultValue = "10") Integer size) throws ParseException {
        Page<PoultryDateSaleVo> page = new Page<>(current, size);
        Object list = recordService.findCountsGroupByDay(stallsName, contacts, startDate, endDate,page);
        return new CommonResult<Object>(ResultEnum.SUCCESS,list);
    }

    @ApiOperation(value = "根据一系列关键词模糊匹配，查询某个时间段贴标的数量总数",notes = "第二版本")
    @GetMapping("/findCountsByDate")
    public CommonResult<Object> findCounts(@RequestParam(value = "stallsName", required = false) String stallsName,
                                           @RequestParam(value = "contacts", required = false) String contacts,
                                           @RequestParam(value = "startDate", required = false) Date startDate,
                                           @RequestParam(value = "endDate", required = false) Date endDate,
                                           @RequestParam(value = "current", defaultValue = "1") Integer current,
                                           @RequestParam(value = "size", defaultValue = "10") Integer size) throws ParseException {
        Page<PoultrySaleVo2> page = new Page<>(current,size);
        Page<PoultryParentVo> tableData = new Page<>(current,size);
        IPage<PoultrySaleVo2> poultryParentList = recordService.findCounts(stallsName, contacts, startDate, endDate, page);
        List<PoultrySaleVo2> records = poultryParentList.getRecords();
        //先查出一段时间内，各（父级）禽类销售数量和对应id；
        //然后再根据id查询出父级名字，将id和名字加入到List集合中。
        List<PoultryParentVo> parentVoList = new ArrayList<PoultryParentVo>();
        for (PoultrySaleVo2 record : records) {
            String id = record.getParentId();
            String parentName = parentService.findNameById(id);
            PoultryParentVo parentVo = new PoultryParentVo();
            parentVo.setParentId(id);
            parentVo.setParentName(parentName);
            parentVoList.add(parentVo);
        }
        //current当前页和size展示条数是共用的
        //现在要对parentVoList（存有id和name）进行分页操作
        //count是list集合中元素的数量
        int count = parentVoList.size();
        List<PoultryParentVo> pageList = new ArrayList<>();
        int currId = current > 1 ? (current - 1)*size : 0;
        for(int i = 0; i < size && i < count - currId; i++){
            pageList.add(parentVoList.get(currId + i));
        }
        //设置分页属性
        tableData.setSize(size);
        tableData.setCurrent(current);
        tableData.setTotal(count);
        tableData.setPages(count % 10 == 0 ? count / 10: count / 10 + 1);
        tableData.setRecords(pageList);
        int sum = 0;
        Map<String, Integer> map = new HashMap<>();
        for (PoultrySaleVo2 record : records) {
            map.put(record.getParentId(), record.getSaleCount());
            sum = sum + record.getSaleCount();
        }
        map.put("sum",sum);
        int countMap = map.size();
        List<Map<String,Integer>> listMap = new ArrayList<>();
        listMap.add(map);

        //跟上面处理一样，只不过直接把map加进去就行了
        Page<Map<String,Integer>> table = new Page<Map<String, Integer>>();
        table.setCurrent(current);
        table.setTotal(countMap);
        table.setPages(count % 10 == 0 ? count / 10: count / 10 + 1);
        table.setRecords(listMap);

        Hashtable<String,Object> data = new Hashtable<>();
        //data.put("table",poultryParentList);
        data.put("table", table);
        data.put("tableData",tableData);

        return new CommonResult<Object>(ResultEnum.SUCCESS, data);
    }


    @Deprecated
    @ApiOperation(value = "根据档口名字or联系人的名字or开始日期or结束日期模糊匹配，查询某个时间段贴标的数量总数")
    @GetMapping("/findCountsBySEDate")
    public CommonResult<IPage<PoultrySaleVo>> findCountsByLikeNameAndSEDate(@RequestParam(value = "stallsName", required = false) String stallsName,
                                                                           @RequestParam(value = "contacts", required = false) String contacts,
                                                                           @RequestParam(value = "startDate", required = false) Date startDate,
                                                                           @RequestParam(value = "endDate", required = false) Date endDate,
                                                                           @RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                           @RequestParam(value = "size", defaultValue = "10") Integer size) throws ParseException {
        Page<PoultrySaleVo> page = new Page<>(current,size);
        IPage<PoultrySaleVo> poultryParentList = recordService.findCountsByTime(stallsName, contacts, startDate, endDate, page);
        return new CommonResult<IPage<PoultrySaleVo>>(ResultEnum.SUCCESS, poultryParentList);
    }

    @Deprecated
    @ApiOperation(value = "根据档口名字or联系人的名字or开始日期or结束日期模糊匹配，以日期查询某个时间段贴标的数量", notes = "分页")
    @GetMapping("/findByMultiKeyWord")
    public CommonResult<IPage<PoultryDateSaleVo>> findByMultiKeyWord(@RequestParam(value = "stallsName", required = false) String stallsName,
                                                                     @RequestParam(value = "contacts", required = false) String contacts,
                                                                     @RequestParam(value = "startDate", required = false) Date startDate,
                                                                     @RequestParam(value = "endDate", required = false) Date endDate,
                                                                     @RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                     @RequestParam(value = "size", defaultValue = "10") Integer size) throws ParseException {
        Page<PoultryDateSaleVo> page = new Page<>(current, size);
        IPage<PoultryDateSaleVo> pages = recordService.findByMultiKeyWord(stallsName, contacts, startDate, endDate,page);
        return new CommonResult<IPage<PoultryDateSaleVo>>(ResultEnum.SUCCESS, pages);
    }


    @ApiOperation(value = "查询全部档口这个月的条码", notes = "分页")
    @GetMapping("/findMonthlyOnPagination")
    public CommonResult<IPage<BarcodeCountVo>> findMonthly(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                           @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<BarcodeCountVo> page = new Page<>(current, size);
        IPage<BarcodeCountVo> pages = recordService.findMonthly(page);
        return new CommonResult<IPage<BarcodeCountVo>>(ResultEnum.SUCCESS, pages);
    }

    @ApiOperation(value = "查询全部档口的条码", notes = "分页")
    @GetMapping("/findAllOnPagination")
    public CommonResult<IPage<BarcodeCountVo>> findAllOnPagination(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                   @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<BarcodeCountVo> page = new Page<>(current, size);
        IPage<BarcodeCountVo> pages = recordService.findAllOnPagination(page);
        return new CommonResult<IPage<BarcodeCountVo>>(ResultEnum.SUCCESS, pages);
    }

    @ApiOperation(value = "根据id查询某个贴标用在了哪个档口")
    @GetMapping(value = "/findById/{id}")
    public CommonResult<BarcodeCountVo> findById(@PathVariable String id) {
        BarcodeCountVo barcodeCountVo = recordService.findById(id);
        return new CommonResult<BarcodeCountVo>(ResultEnum.SUCCESS, barcodeCountVo);
    }

    @ApiOperation(value = "根据id查询详细数据")
    @GetMapping(value = "/findDetailedRecordById/{id}")
    public CommonResult<DetailedRecordVo> findDetailedRecordById(@PathVariable String id) {
        DetailedRecordVo dr = recordService.findDetailedRecordById(id);
        return new CommonResult<DetailedRecordVo>(ResultEnum.SUCCESS, dr);
    }

    @ApiOperation(value = "回显条形码发放（用于修改贴标信息）")
    @GetMapping("/findRecordById/{id}")
    public CommonResult<LabelingRecord> findRecordById(@PathVariable String id){
        LabelingRecord grant = recordService.getById(id);
        return new CommonResult<LabelingRecord>(ResultEnum.SUCCESS,grant);
    }

    @ApiOperation(value = "增加")
    @PostMapping("/addRecord")
    public CommonResult<String> add(@RequestBody @Validated LabelingRecord record) {
        if (recordService.save(record)) {
            return new CommonResult<String>(ResultEnum.SUCCESS);
        }
        return new CommonResult<String>(ResultEnum.ERROR);
    }

    @ApiOperation(value = "根据传进来的id修改")
    @PutMapping("/updateById")
    public CommonResult<String> updateById(@RequestBody LabelingRecord record) {
        if (recordService.updateById(record)) {
            return new CommonResult<String>(ResultEnum.SUCCESS);
        }
        return new CommonResult<String>(ResultEnum.ERROR);
    }

    @ApiOperation(value = "删除")
    @DeleteMapping(value = "/deleteById/{id}")
    public CommonResult<String> deleteById(@PathVariable(value = "id") String id) {
        if (recordService.removeById(id)) {
            return new CommonResult<String>(ResultEnum.SUCCESS);
        }
        return new CommonResult<String>(ResultEnum.ERROR);
    }

    @ApiOperation(value = "查询条码详细信息", notes = "分页")
    @GetMapping("/findAllDROnPagination")
    public CommonResult<IPage<DetailedRecordVo>> findAllDROnPagination(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                       @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<DetailedRecordVo> page = new Page<>(current, size);
        IPage<DetailedRecordVo> pages = recordService.findAllDROnPagination(page);
        return new CommonResult<IPage<DetailedRecordVo>>(ResultEnum.SUCCESS, pages);
    }

    @ApiOperation(value = "基于条码详细信息数据进行模糊检索", notes = "分页")
    @GetMapping("/findDRByLikeNameOnPagination")
    public CommonResult<IPage<DetailedRecordVo>> findDRByLikeNameOnPagination(@RequestParam(value = "keyWord", required = false) String keyWord,
                                                                              @RequestParam(value = "current", defaultValue = "1") Integer current,
                                                                              @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<DetailedRecordVo> page = new Page<>(current, size);
        IPage<DetailedRecordVo> pages = null;
        if (null == keyWord) {
            pages = recordService.findAllDROnPagination(page);
        } else {
            pages = recordService.findAllDRByLikeNameOnPagination(page, keyWord);
        }
        return new CommonResult<IPage<DetailedRecordVo>>(ResultEnum.SUCCESS, pages);
    }



    @ApiOperation("二维码溯源")
    @GetMapping("/getSrc/{barcodeNumber}")
    public CommonResult<TraceSrcVo> getSrc(@PathVariable String barcodeNumber) {
        TraceSrcVo srcVo = recordService.getSrc(barcodeNumber);
        return new CommonResult<TraceSrcVo>(ResultEnum.SUCCESS,srcVo);
    }


}

